package cn.com.my.yes1;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 * json-simple实现json写入读出(转换！)
 * 字符与对象之间转换
 * @author chenhs
 * @time 2015年7月8日 下午5:22:37
 */
public class JsonSimpleExample {
	
	@SuppressWarnings("unchecked")
	public static void writeJson(){
		JSONObject obj = new JSONObject();
		obj.put("name", "mkyong.com");
		obj.put("age", new Integer(100));
	 
		JSONArray list = new JSONArray();
		list.add("msg 1");
		list.add("msg 2");
		list.add("msg 3");
		obj.put("messages", list);
	 
		try {
			FileWriter file = new FileWriter("c:\\test.json");
			file.write(obj.toString());
			file.flush();
			file.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	 
		System.out.print(obj);
	}
	
	
	@SuppressWarnings("unchecked")
	public static void readJson(){
		JSONParser parser = new JSONParser();
		 
		try {
			Object obj = parser.parse(new FileReader("c:\\test.json"));
			JSONObject jsonObject = (JSONObject) obj;
	 
			String name = (String) jsonObject.get("name");
			System.out.println(name);
	 
			long age = (Long) jsonObject.get("age");
			System.out.println(age);
	 
			// loop array
			JSONArray msg = (JSONArray) jsonObject.get("messages");
			Iterator<String> iterator = msg.iterator();
			while (iterator.hasNext()) {
				System.out.println(iterator.next());
			}
	 
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
//		writeJson();
		readJson();
	}

}
